package com.itheima.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Service.ClazzService;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper  studentMapper;


    @Override
    public PageBean page(ClazzQueryParam param) {
        //1. 设置分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());

        //2. 执行查询
        List<Clazz> clazzList = clazzMapper.list(param);

        //3. 解析封装分页结果
        Page<Clazz> p = (Page<Clazz>) clazzList;

        return new PageBean(p.getTotal(), p.getResult());
    }

//    @Override
//    public PageBean page(String name, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
//        //1. 设置分页参数
//        PageHelper.startPage(page,pageSize);
//
//        //2. 执行查询
//        List<Clazz> clazzList = clazzMapper.list(name,begin,end);
//        Page<Clazz> p = (Page<Clazz>) clazzList;
//
//        //3. 封装结果
//        return new PageBean(p.getTotal(), p.getResult());
//    }




    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        //1. 判断该班级下是否有学生
        Integer count = studentMapper.countByClazzId(id);

        //2. 如果有, 提示错误信息
        if (count > 0) {
            //抛异常
            throw new BusinessException("对不起, 该班级下有学生, 不能直接删除");
        }

        //3. 没有, 再删除
        clazzMapper.deleteById(id);
    }
    @Override
    public Clazz getInfo(Integer id) {

        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> list() {
        return clazzMapper.list(null);

    }

}
